<script setup lang="ts">
import lodash from 'lodash-es'

/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
defineOptions({
  name: "BillConfig",
  inheritAttrs: false,
});
import {ElLoading, UploadFile} from "element-plus";
import 'element-plus/theme-chalk/el-loading.css';
import {getDictOptions} from "@/api/dict";
import {getBillColumnList} from "@/api/bill";
import {getOrderColumnList} from "@/api/order";
import {saveColumnMatch, getBaseColumnList, deleteBaseColumn, check, billImport, billExport} from "@/api/baseColumnMatch";
import {getColumnMatchConditionList, deleteColumnMatchCondition} from "@/api/columnMatchCondition";
import {saveBillColumnMatch, getBillColumnMatchList, deleteBillColumn} from "@/api/billColumnMatch";
import {saveColumnAppend, getColumnAppendList, deleteColumnAppend} from "@/api/columnAppend";
import { BaseColumnMatchVO } from "@/api/baseColumnMatch/types";
import { ColumnMatchConditionVO } from "@/api/columnMatchCondition/types";
import { BillColumnMatchVO } from "@/api/billColumnMatch/types";
import { ColumnAppendVO } from "@/api/columnAppend/types";
import { CommonList } from "@/api/common/types";

const activeTab = ref('one')
const dataFormRef = ref(ElForm);
const dialog = reactive<DialogOption>({
	visible: false,
});
const isBill = ref(true);  // 是否是账单配置
const platformKey = ref('') // 基础字段配置平台key
const baseColumnList = ref<BaseColumnMatchVO[]>([]);  // 基础字段配置列表
const standardColumnList = reactive<CommonList>({value: []})  // 标准字段列表
const sourceColumnList: Ref<OptionType[]> = ref([]); // 原始字段列表
const tmBillConditionDialog = reactive<DialogOption>({
	visible: false,
});
// 天猫账单配置弹窗
const tmBillDialog = reactive<DialogOption>({
	visible: false,
});
// 天猫账单配置导入弹窗
const tmBillImportDialog = reactive<DialogOption>({
	title: '配置导入',
	visible: false,
});
const excelFile = ref<File>();
const excelFilelist = ref<File[]>([]);
const columnConditionList = ref<ColumnMatchConditionVO[]>([]);  // 基础字段符合条件配置列表
const conditionSourceType = ref('') // 符合条件来源类型
const matchId = ref(0);
const billColumnList = ref<BillColumnMatchVO[]>([]);  // 账单项目配置列表
const billConditionDialog = reactive<DialogOption>({
	visible: false,
});
const billProjectList = reactive<CommonList>({value: []})  // 记账项目字段列表
const platformName = ref('')

// 获取基础字段配置列表
async function getBaseColumn() {
	getBaseColumnList(platformKey.value).then((response) => {
		baseColumnList.value = response.data
		if (baseColumnList.value && baseColumnList.value.length > 0) {
			for (const baseColumn of baseColumnList.value) {
				lodash.set(baseColumn, 'isUpdate', false)
		  	lodash.set(baseColumn, 'need', baseColumn.dataGeneration === '通过计算')
			}
		}
	})
}

// tab点击事件
function tabClick(e?: any) {
	if (e.props.name === 'three') {
		// 获取账单项目配置的记账项目字段列表+原始字段
		const filterList = lodash.filter(billColumnList.value, (o: BillColumnMatchVO) => o.id)
		billProjectList.value = lodash.map(filterList, (o: BillColumnMatchVO) => o.originalBillProject)
		for (const sourceColumn of sourceColumnList.value) {
			if (!billProjectList.value.includes(sourceColumn.value)) {
		  	billProjectList.value.push(sourceColumn.value)
			}
		}
	}
}

/**
 * Excel文件change事件
 *
 * @param file
 */
function handleExcelChange(file: UploadFile) {
	if (file.size !== undefined) {
		if (file.size > 20*1024*1024) {
			ElMessage.warning("上传文件大小已经超过20M，请尝试拆分成多个文件再上传");
			return false
		}
	}
	if (!/\.(csv|xlsx|xls|XLSX|XLS|CSV)$/.test(file.name)) {
		ElMessage.warning("上传Excel只能为xlsx、xls、csv格式");
		excelFile.value = undefined;
		excelFilelist.value = [];
		return false;
	}
	excelFile.value = file.raw;
}

// 关闭天猫账单配置弹窗
function closeTmBillDialog() {
	check(platformKey.value).then((response) => {
		if (response.data) {
			ElMessageBox.confirm(
				response.data,
				{
					confirmButtonText: '继续编辑',
					cancelButtonText: '暂时关闭',
					type: 'warning',
					closeOnClickModal: false,
					closeOnPressEscape: false
				}
			)
				.then(() => {})
				.catch(() => {
					tmBillDialog.visible = false;
				})
		}else{
			tmBillDialog.visible = false;
		}
	})
}

// 打开天猫账单配置弹窗
function openImportTmBillConfig() {
	tmBillImportDialog.visible = true;
	tmBillImportDialog.title = platformName.value + '配置导入'
}

// 关闭天猫账单配置弹窗
function closeTmBillImport() {
	tmBillImportDialog.visible = false;
	excelFile.value = undefined;
	excelFilelist.value = [];
	getBaseColumn()
}

function handleTmBillImport() {
	if (!excelFile.value) {
		ElMessage.warning("上传Excel文件不能为空");
		return false;
	}
	const importLoading = ElLoading.service({
		lock: true,
		text: '导入中...',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	billImport(excelFile.value, platformKey.value).then((response) => {
	  closeTmBillImport();
		ElMessage.success('导入成功');
	}).finally(() => importLoading.close());
}

// 打开天猫账单配置弹窗
async function openTmBillDialog(platform, key) {
	tmBillDialog.title = platform + "配置";
	platformName.value = platform
	platformKey.value = key
	tmBillDialog.visible = true;
	activeTab.value = 'one'
	await getBaseColumn()
}

function handleExportTmBill(){
	billExport(platformKey.value).then((response: any) => {
		const blob = new Blob([response.data], {
			type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
		});
		const a = document.createElement("a");
		const href = window.URL.createObjectURL(blob); // 下载的链接
		a.href = href;
		a.download = decodeURI(
			response.headers["content-disposition"].split(";")[1].split("=")[1]
		); // 获取后台设置的文件名称
		document.body.appendChild(a);
		a.click(); // 点击导出
		document.body.removeChild(a); // 下载完成移除元素
		window.URL.revokeObjectURL(href); // 释放掉blob对象
	});
}

// 打开天猫账单符合条件弹窗
async function openTmBillConditionDialog(id?: number, sourceType?: string) {
	if (!id) {
		ElMessage.warning("请先保存数据");
		return
	}
	matchId.value = id
	tmBillConditionDialog.visible = true;
	tmBillConditionDialog.title = "基础字段符合条件配置";
	if (sourceType) {
		conditionSourceType.value = sourceType
	}
	columnConditionList.value = []
	getColumnMatchConditionList(matchId.value, conditionSourceType.value).then((response) => {
		columnConditionList.value = response.data;
	});
}

onMounted(() => {
});
</script>

<template>
  <div class="app-container">
	  <el-card class="box-card" style="float: left;margin-right: 5px;">
		  <template #header>
			  <div class="card-header">
				  <span>OMS销售订单</span>
			  </div>
		  </template>
		  <div>
				<el-button type="primary" @click="openTmBillDialog('OMS销售订单', 'omsOrder')">字段配置</el-button>
			</div>
	  </el-card>
	  <el-card class="box-card" style="float: left;margin-right: 5px;">
		  <template #header>
			  <div class="card-header">
				  <span>OMS售后单</span>
			  </div>
		  </template>
		  <div>
				<el-button type="primary" @click="openTmBillDialog('OMS售后单', 'omsReturnOrder')">字段配置</el-button>
			</div>
	  </el-card>

	  <!--OMS原始单据配置-->
	  <el-dialog
			  v-model="tmBillDialog.visible"
			  :title="tmBillDialog.title"
			  width="700px"
			  :close-on-click-modal="false"
			  :before-close="closeTmBillDialog"
	  >
		  <el-form
				  ref="dataFormRef"
				  label-width="160px"
		  >
			  <el-tabs type="border-card" v-model="activeTab" @tab-click="tabClick">
				  <el-tab-pane label="基础字段配置" name="one">
					  <el-card shadow="never" >
						  <div style="margin-bottom: 10px" class="flex justify-between">
							  <div>
								  <el-button type="primary" @click="openImportTmBillConfig" v-hasPerm="['sys:baseColumnMatch:omsConfigImport']">导入</el-button>
								  <el-button type="primary" @click="handleExportTmBill" v-hasPerm="['sys:baseColumnMatch:omsConfigExport']">导出</el-button>
							  </div>
						  </div>
						  <el-table
								  row-style="height: 41px;"
								  size="small"
								  :header-row-style="{color: 'dimgray'}"
								  border
								  :data="baseColumnList"
						  >
							  <el-table-column
									  label="原始字段"
									  align="center" show-overflow-tooltip
										prop="sourceColumn"
							  />
							  <el-table-column
									  label="标准字段"
									  align="center" show-overflow-tooltip
										prop="standardColumn"
							  />
							  <el-table-column label="操作" width="120" fixed="right" align="center">
								  <template #default="scope">
									  <el-button
												v-if="scope.row.dataGeneration !== '通过计算'"
											  type="primary"
											  size="small"
											  @click="openTmBillConditionDialog(scope.row.id, 'base')"
									  >符合条件</el-button>
								  </template>
							  </el-table-column>
						  </el-table>
					  </el-card>
				  </el-tab-pane>
			  </el-tabs>

		  </el-form>
	  </el-dialog>

	  <!--符合条件弹窗-->
	  <el-dialog
			  v-model="tmBillConditionDialog.visible"
			  :title="tmBillConditionDialog.title"
			  width="800px"
			  draggable
			  :close-on-click-modal="false"
			  @close="tmBillConditionDialog.visible = false"
	  >
		  <el-card shadow="never" >
			  <el-table
					  row-style="height: 41px;"
					  size="small"
					  :header-row-style="{color: 'dimgray'}"
					  border
					  :data="columnConditionList"
			  >
				  <el-table-column
						  label="条件"
						  align="center" show-overflow-tooltip
							prop="conditions"
				  />
				  <el-table-column
						  label="变量"
						  align="center" show-overflow-tooltip
							width="200"
							prop="params"
				  />
			  </el-table>
		  </el-card>
	  </el-dialog>

	  <!-- OMS原始单据配置导入弹窗 -->
	  <el-dialog
			  v-model="tmBillImportDialog.visible"
			  :title="tmBillImportDialog.title"
			  width="600px"
			  append-to-body
			  @close="closeTmBillImport"
	  >
		  <el-form label-width="80px">

			  <el-form-item label="Excel">
				  <el-upload
						  class="upload-demo"
						  action=""
						  drag
						  :auto-upload="false"
						  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
						  :file-list="excelFilelist"
						  :on-change="handleExcelChange"
						  :limit="1"
				  >
					  <el-icon class="el-icon--upload">
						  <i-ep-upload-filled />
					  </el-icon>
					  <div class="el-upload__text">
						  将文件拖到此处，或
						  <em>点击上传</em>
					  </div>
					  <template #tip>
						  <div class="el-upload__tip">xls/xlsx files</div>
					  </template>
				  </el-upload>
			  </el-form-item>
		  </el-form>
		  <template #footer>
			  <div class="dialog-footer">
				  <el-button type="primary" @click="handleTmBillImport">确 定</el-button>
				  <el-button @click="closeTmBillImport">取 消</el-button>
			  </div>
		  </template>
	  </el-dialog>
  </div>
</template>
